package com.smt.modules.app.controller;

import com.aliyuncs.dysmsapi.model.v20170525.SendSmsResponse;
import com.google.code.kaptcha.impl.DefaultKaptcha;
import com.smt.common.enums.Code;
import com.smt.common.utils.*;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.util.Enumeration;

/**
 * 生成验证码
 *
 * @author zhangyi
 * @date 2018/10/19 14:51
 */
@RestController
@Slf4j
@RequestMapping("/app/verification")
@Api(description = "生成验证码(客户端接口)")
public class AppVerificationCodeController {
    @Autowired
    DefaultKaptcha defaultKaptcha;

    @Autowired
    private EmailUtil emailUtil;

    @Autowired
    private RedisUtils redisUtils;


    /**
     * 图片验证码生成
     *
     * @param httpServletRequest
     * @param httpServletResponse
     * @throws Exception
     */
    @PostMapping("/code")
    @ApiOperation(value = "图片验证码生成",httpMethod = "POST")
    public void code(HttpServletRequest httpServletRequest,
                               HttpServletResponse httpServletResponse) throws Exception{
        byte[] captchaChallengeAsJpeg = null;
        ByteArrayOutputStream jpegOutputStream = new ByteArrayOutputStream();
        try {
            //生产验证码字符串并保存到session中
            String createText = defaultKaptcha.createText();
            httpServletRequest.getSession().setAttribute(Constant.VAR_CODE, createText);
            BufferedImage challenge = defaultKaptcha.createImage(createText);
            ImageIO.write(challenge, "jpg", jpegOutputStream);
        } catch (IllegalArgumentException e) {
            httpServletResponse.sendError(HttpServletResponse.SC_NOT_FOUND);
            return;
        }
        //定义response输出类型为image/jpeg类型，使用response输出流输出图片的byte数组
        captchaChallengeAsJpeg = jpegOutputStream.toByteArray();
        httpServletResponse.setHeader("Cache-Control", "no-store");
        httpServletResponse.setHeader("Pragma", "no-cache");
        httpServletResponse.setDateHeader("Expires", 0);
        httpServletResponse.setContentType("image/jpeg");
        ServletOutputStream responseOutputStream =
                httpServletResponse.getOutputStream();
        responseOutputStream.write(captchaChallengeAsJpeg);
        responseOutputStream.flush();
        responseOutputStream.close();
    }

    /**
     *  发送验证码
     *
     * @param emailStr
     * @param phoneStr
     * @return
     */
    @PostMapping("/sendCode")
    @ApiOperation(value = "发送验证码",httpMethod = "POST")
    public R sendCode(String emailStr,String phoneStr,HttpServletRequest request){
        String text = RandomUtil.randomNumber(6);
        if(emailStr != null && ExistSessionKeyUtil.get(request,emailStr) == null){
            if(!isEmail(emailStr)){
                return R.error(EnumToKeyUtil.toInt(Code.REQUEST_PARAM_ERROR),"邮箱格式输入错误");
            }
            emailUtil.sendSimpleMail(emailStr,"尊敬的用户，易树智造","您的验证码："+text);
            request.getSession().setAttribute(emailStr,text);
            request.getSession().setMaxInactiveInterval(Constant.MINUTE_S*3);
            return R.ok("邮箱发送成功");
        }else if (phoneStr != null && ExistSessionKeyUtil.get(request,phoneStr) == null){
            if (isEmail(phoneStr)){
                return R.error(EnumToKeyUtil.toInt(Code.REQUEST_PARAM_ERROR),"手机号输入错误！");
            }
            SendSmsResponse sendSmsResponse = AliyunSmsUtil.sendCodeSms(phoneStr, text);
            if("OK".equals(sendSmsResponse.getCode())){
                request.getSession().setAttribute(phoneStr,text);
                request.getSession().setMaxInactiveInterval(Constant.MINUTE_S*3);
                return R.ok("短信发送成功");
            }else{
                return R.error(9870,"短信发送失败");
            }
        }
        return R.error(9870,"发送失败");
    }

    /**
     * 判断邮箱
     *
     * @param str
     * @return
     */
    private boolean isEmail(String str){
        if(StringUtils.contains(str,"@")){
            return true;
        }
        return false;
    }
}
